
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDateTime>

void MainWindow::clientConnected()
{   
    QTcpSocket *sock = server.nextPendingConnection();
    connect(sock, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    connect(sock, SIGNAL(readyRead()), this, SLOT(dataReceived()));
    ++playerCount;
    newPlayerConnected = true;
}

void MainWindow::dataReceived()
{
    QTcpSocket *sock = dynamic_cast<QTcpSocket*>(sender());

   // addToLog("Received data from socket ");
    while (sock->canReadLine()) {
        QString str = sock->readLine().trimmed();
        int erre;

        if (str.startsWith("*USER ")) {
            QString nombre;
            nombre = str.trimmed();
            erre = nombre.indexOf('R');
            nombre = nombre.mid(erre + 2) + "^";
            connectedPlayers.push_back(nombre);
            sock->write("+OK\n");
        } else if (str.startsWith("*PASS ")) {
            if (str.endsWith(" 12345")) {
                sock->write("+OK\n");
            } else {
                sock->write("-ERR\n");
            }
        } else {

            // send data to all connected clients
            for (QObject *obj : server.children()) {
                QTcpSocket *anotherSock = dynamic_cast<QTcpSocket*>(obj);
                if (anotherSock != NULL) {

                    //Sends the number of clients connected and the way the program should set up players;
                    if(newPlayerConnected){
                        QString playersForGame = "";

                        for(int i = 0; i < playerCount; i++){
                            playersForGame = playersForGame + connectedPlayers[i];
                        }
                        playersForGame = QString::number(playerCount) + "^" + playersForGame + "#";
                        anotherSock->write(playersForGame.toLatin1());
                    }

                    str += "\n";
                    anotherSock->write(str.toLatin1());
                }
            }
            newPlayerConnected = false;
        }
    }
}

void MainWindow::clientDisconnected()
{
    QTcpSocket *sock = dynamic_cast<QTcpSocket*>(sender());
    sock->deleteLater();
    --playerCount;
}

